package com.bjc.netty.chat.protocol;

import com.bjc.netty.chat.message.LoginRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

/**
 * @program: nettypro
 * @description: 测试自定义协议
 * @author: bjc
 * @create: 2021-09-25 21:40
 */
public class TestMessageCode {

    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(), //放LengthFieldBasedFrameDecoder上面能把两次接受消息分别打印出来  放下面只有消息全部接收到才打印
                //解决黏包 半包
                new LengthFieldBasedFrameDecoder(1024,12,4,0,0),
                new MessageCodec());
        // encode
        LoginRequestMessage message = new LoginRequestMessage("zhangsan", "123");
        channel.writeOutbound(message);

        // decode
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new MessageCodec().encode(null,message,buf);

        //入栈
//        channel.writeInbound(buf);

        // 模拟半包发送
        ByteBuf s1 = buf.slice(0, 100);
        ByteBuf s2 = buf.slice(100, buf.readableBytes()-100);
        s1.retain(); //引用计数 +1
        channel.writeInbound(s1); //这里会release  引用计数-1
        channel.writeInbound(s2);
    }
}
